package com.zy.edu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.CourseChapterDao;
import com.zy.edu.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-07-20
 */
@Service
@Transactional
public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterDao, CourseChapter> implements CourseChapterService {
    @Resource
    UserService userService;

    @Resource
    CourseChapterVideoService courseChapterVideoService;

    @Resource
    CourseChapterDocService courseChapterDocService;

    @Resource
    CourseChapterClassService courseChapterClassService;

    @Resource
    CourseChapterSignService courseChapterSignService;
    @Resource
    CourseChapterHomeworkService courseChapterHomeworkService;

    @Override
    public Map saveOrUpdate(CourseChapter chapter, InputParam inputParam) {

        if(StringUtils.isEmpty(chapter.getCourseId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }

        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //只有超管和校管可以上传课时
        if(currentUser.getRoleType().equals(Role.SUPER)
                ||currentUser.getRoleType().equals(Role.SCHOOL)) {
            if (StringUtils.isEmpty(chapter.getId())) {
                chapter.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                chapter.setCreateTime(new Date());
                chapter.setStatus(1);
                this.baseMapper.insert(chapter);
                //新增课时的时候，要为已有该课程的班级也新增记录数量
                //course_chapter_class
                addCourseChapterClass(chapter,inputParam);
            } else {
                this.baseMapper.updateById(chapter);
            }
            return ResponseInfo.success(null);
        }else {
            return ResponseInfo.error("您无权限创建课时");
        }
    }

    //新增课时的时候，要为已有该课程的班级也新增记录数量
    private void addCourseChapterClass(CourseChapter chapter, InputParam inputParam){
        List<CourseChapterClass> classIds = courseChapterClassService.findClassIdsByCourseId(inputParam);
        List<CourseChapterClass> res = new ArrayList<>();
        for (CourseChapterClass classInfo : classIds) {
            CourseChapterClass ccc = new CourseChapterClass();
            ccc.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            ccc.setChapterId(chapter.getId());
            ccc.setClassId(classInfo.getClassId());
            ccc.setCourseId(chapter.getCourseId());
            ccc.setStatus(0);//未上课
            ccc.setCreateTime(new Date());
            res.add(ccc);
        }
        if(res.size()>0) {
            courseChapterClassService.insertBatch(res);
        }

    }

    @Override
    public Map list(CourseChapter chapter, InputParam inputParam) {
        if(StringUtils.isEmpty(chapter.getCourseId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
        EntityWrapper<CourseChapter> entityWrapper = new EntityWrapper<CourseChapter>();
        if(!StringUtils.isEmpty(chapter.getName())){
            entityWrapper.like("name",chapter.getName());
        }
        entityWrapper.eq("course_id",chapter.getCourseId());
        entityWrapper.eq("status",1);
        entityWrapper.orderBy("num",true);
        List<CourseChapter> chapterList = this.baseMapper.selectList(entityWrapper);
        return ResponseInfo.success(chapterList);
    }

    @Override
    public Map dele(CourseChapter chapter) {
        if(!StringUtils.isEmpty(chapter.getId())){
            //设置为不可用
            chapter.setStatus(0);
            this.baseMapper.updateById(chapter);

            //删除course_chapter_class里的所有关联数据
            courseChapterClassService.delete(
                    new EntityWrapper<CourseChapterClass>()
                            .eq("chapter_id",chapter.getId()));
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map getById(CourseChapter courseChapter, InputParam inputParam) {
        if(StringUtils.isEmpty(courseChapter.getId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            CourseChapter temp = this.selectById(courseChapter.getId());
            List<CourseChapterVideo> videoList = courseChapterVideoService.selectList(
                    new EntityWrapper<CourseChapterVideo>()
                            .eq("chapter_id", courseChapter.getId())
                            .eq("status", 1)
                            .orderBy("num",true));

            temp.setVideoList(videoList);
            //PDF PPT的读取
            List<CourseChapterDoc> docList = courseChapterDocService.selectList(
                    new EntityWrapper<CourseChapterDoc>()
                            .eq("chapter_id", courseChapter.getId())
                            .eq("status", 1)
                            .orderBy("num",true));
            temp.setDocList(docList);

            //作业的读取
            List<CourseChapterHomework> homeList = courseChapterHomeworkService.selectList(
                    new EntityWrapper<CourseChapterHomework>()
                            .eq("chapter_id", courseChapter.getId())
                            .eq("status", 1)
                            .orderBy("num",true));
            temp.setHomeList(homeList);

            return ResponseInfo.success(temp);
        }

    }

    @Override
    public Map sign(CourseChapterSign courseChapterSign,InputParam inputParam) {
        if(StringUtils.isEmpty(courseChapterSign.getUserId())
            ||StringUtils.isEmpty(courseChapterSign.getChapterId())
                ||StringUtils.isEmpty(courseChapterSign.getCourseId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {

            //当前用户的信息
            User currentUser = userService.selectById(courseChapterSign.getUserId());
            //学生的签到接口
            if(currentUser.getRoleType().equals(Role.STUDENT)){
                List<CourseChapterSign> signList = courseChapterSignService.selectList(new EntityWrapper<CourseChapterSign>()
                        .eq("user_id", courseChapterSign.getUserId())
                        .eq("chapter_id", courseChapterSign.getChapterId()));
                if(signList.size()>0){
                    return ResponseInfo.success(null);
                }
                courseChapterSign.setCreateTime(new Date());
                courseChapterSign.setSign(1);
                currentUser.setClassId(currentUser.getClassId());
                courseChapterSignService.insert(courseChapterSign);
            }
            //教师签到
            if(currentUser.getRoleType().equals(Role.TEACHER)){
                List<CourseChapterClass> list = courseChapterClassService.selectList(
                        new EntityWrapper<CourseChapterClass>()
                                .eq("class_id",inputParam.getClassId())
                                .eq("course_id",inputParam.getCourseId())
                                .eq("chapter_id",inputParam.getChapterId()));
                if(list.size()>0){
                    CourseChapterClass courseChapterClass = list.get(0);
                    if(courseChapterClass.getStatus()!=1) {
                        //修改为上课状态
                        courseChapterClass.setStatus(1);
                        courseChapterClassService.updateById(courseChapterClass);
                    }
                }
            }
            return ResponseInfo.success(null);
        }
    }

    @Override
    public int countByCourseId(String courseId) {
        if(!StringUtils.isEmpty(courseId)) {
            EntityWrapper<CourseChapter> entityWrapper = new EntityWrapper<CourseChapter>();
            entityWrapper.eq("course_id",courseId);
            entityWrapper.eq("status",1);
            Integer count = this.baseMapper.selectCount(entityWrapper);
            return count;
        }
        return 0;
    }
}
